<template>
  <div class="grandchild-component">
    <div class="flex justify-between items-center mb-4">
      <h4 class="m-0 text-gray-800 font-semibold">孙组件 (GrandChild Component)</h4>
      <span class="badge">👶👶 GrandChild</span>
    </div>

    <!-- 孙组件生命周期状态 -->
    <div class="bg-white bg-opacity-30 p-2 rounded mb-2">
      <h5 class="mb-2 text-red-700 text-xs font-medium">孙组件生命周期：</h5>
      <div class="flex flex-wrap gap-1">
        <span
          v-for="status in grandChildLifecycleStatus"
          :key="status.name"
          :class="['status-badge', status.executed ? 'executed' : 'pending']"
        >
          {{ status.name }}: {{ status.executed ? '✅' : '⏳' }}
        </span>
      </div>
    </div>

    <!-- 从子组件接收的数据 -->
    <div class="bg-white bg-opacity-30 p-2 rounded mb-2">
      <h5 class="mb-1 text-red-700 text-xs font-medium">接收的数据: {{ data }}</h5>
      <p class="m-0 text-xs font-mono">更新次数: {{ grandChildState }}</p>
    </div>

    <!-- 孙组件按钮 -->
    <div class="flex gap-2 mb-2 flex-wrap">
      <button @click="updateGrandChildState" class="grandchild-btn">更新孙组件</button>
      <button @click="emitToChild" class="grandchild-btn">发事件给子组件</button>
    </div>

    <!-- 渲染顺序提示 -->
    <div class="text-center p-2 bg-white bg-opacity-20 rounded">
      <small class="text-gray-600 italic text-xs">🔍 查看控制台了解完整的渲染顺序</small>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  watch,
} from 'vue'

// Props
interface Props {
  data: number
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  grandchildEvent: [data: { type: string; payload: any }]
}>()

// 孙组件响应式数据
const grandChildState = ref(0)

// 孙组件生命周期状态
const grandChildLifecycleStatus = reactive([
  { name: 'setup', executed: true },
  { name: 'onBeforeMount', executed: false },
  { name: 'onMounted', executed: false },
  { name: 'onBeforeUnmount', executed: false },
  { name: 'onUnmounted', executed: false },
])

// 辅助函数
const updateGrandChildLifecycleStatus = (name: string) => {
  const status = grandChildLifecycleStatus.find((s) => s.name === name)
  if (status) {
    status.executed = true
  }
}

const logGrandChildLifecycle = (phase: string) => {
  console.log(`        🔸 [GrandChild] ${phase} - ${new Date().toLocaleTimeString()}`)
}

// setup阶段
console.log('        🌿 [GrandChild] setup开始 - 孙组件实例创建')

// 生命周期钩子
onBeforeMount(() => {
  logGrandChildLifecycle('onBeforeMount - 孙组件挂载前')
  updateGrandChildLifecycleStatus('onBeforeMount')
})

onMounted(() => {
  logGrandChildLifecycle('onMounted - 孙组件挂载完成')
  updateGrandChildLifecycleStatus('onMounted')
})

// 注意：onBeforeUpdate 和 onUpdated 会在任何响应式数据变化时触发
// 为避免无限循环，我们只在控制台记录，不更新页面状态
onBeforeUpdate(() => {
  logGrandChildLifecycle('onBeforeUpdate - 孙组件更新前')
  // 移除状态更新，避免无限循环：updateGrandChildLifecycleStatus('onBeforeUpdate')
})

onUpdated(() => {
  logGrandChildLifecycle('onUpdated - 孙组件更新完成')
  // 移除状态更新，避免无限循环：updateGrandChildLifecycleStatus('onUpdated')
})

onBeforeUnmount(() => {
  logGrandChildLifecycle('onBeforeUnmount - 孙组件卸载前')
  updateGrandChildLifecycleStatus('onBeforeUnmount')
})

onUnmounted(() => {
  logGrandChildLifecycle('onUnmounted - 孙组件卸载完成')
  updateGrandChildLifecycleStatus('onUnmounted')
})

// 监听Props
watch(
  () => props.data,
  (newVal, oldVal) => {
    console.log(`        👀 [GrandChild] watch props.data: ${oldVal} -> ${newVal}`)
  },
)

// 方法
const updateGrandChildState = () => {
  grandChildState.value++
  logGrandChildLifecycle(`触发第${grandChildState.value}次状态更新`)
}

const emitToChild = () => {
  const eventData = {
    type: 'grandchild-update',
    payload: {
      state: grandChildState.value,
      timestamp: new Date().toLocaleTimeString(),
    },
  }
  emit('grandchildEvent', eventData)
  console.log('        📤 [GrandChild] 向子组件发送事件:', eventData)
}

console.log('        ✅ [GrandChild] 孙组件setup完成')
</script>

<style scoped lang="scss">
// 复杂渐变背景用sass实现
.grandchild-component {
  @apply rounded p-4 text-gray-800 border-2 border-white border-opacity-50 text-xs;
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

// 徽章样式
.badge {
  @apply px-2 py-1 rounded-xl text-xs font-bold text-gray-800;
  background: rgba(255, 255, 255, 0.8);
}

// 警告提示框样式用sass实现
.update-note {
  @apply rounded p-1 mb-2;
  background: rgba(255, 193, 7, 0.2);
  border: 1px solid rgba(255, 193, 7, 0.4);
}

// 状态徽章样式
.status-badge {
  @apply px-2 py-1 rounded-xl text-xs transition-all duration-300;

  &.pending {
    @apply bg-white bg-opacity-50 text-orange-600;
  }

  &.executed {
    background: rgba(76, 175, 80, 0.8);
    @apply text-white;
  }
}

// 孙组件按钮样式
.grandchild-btn {
  @apply px-3 py-1 rounded-2xl text-gray-800 cursor-pointer transition-all duration-300 text-xs;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.5);

  &:hover {
    @apply bg-white scale-105;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  }
}
</style>
